package ueg.org.trabalho.dao;

import java.util.List;
import org.hibernate.Query;

import org.hibernate.Session;
import org.hibernate.Transaction;

import ueg.org.trabalho.interfaces.IDao;
import ueg.org.trabalho.model.Departamento;

public class DaoDepartamento extends Dao implements IDao<Departamento> {

    @Override
    public void salva(Departamento objeto) throws Exception {
        Session session = super.getSession();
        Transaction tx = session.beginTransaction();
        try {
            session.save(objeto);
            tx.commit();
        } catch (Exception e) {
            tx.rollback();
        } finally {
            session.close();
        }

    }

    @Override
    public void deleta(Departamento objeto) throws Exception {
        Session session = super.getSession();
        Transaction transaction = session.beginTransaction();
        try {
            session.delete(objeto);
            transaction.commit();

        } catch (Exception ex) {
            transaction.rollback();
        } finally {
            session.close();
        }
    }

    @Override
    public List<Departamento> listagem() throws Exception {
        Session session = super.getSession();
        try {
            Query query = session.createQuery("from Departamento");
            return query.list();
        } finally {
            session.close();
        }
    }

    @Override
    public List<Departamento> listagemLike(String campo, String pesquisa, String condicaoPesquisa) throws Exception {
        String hql = null;
        Session session = super.getSession();
        try {
            List results = null;
            if (campo.equals("Nome")) {
                if (condicaoPesquisa.equals("Iniciando Com")) {
                    hql = "select p from Departamento p where  p.nome  like :pesquisa";
                    Query query = session.createQuery(hql);
                    query.setString("pesquisa", pesquisa + "%");
                    results = query.list();
                }
                if (condicaoPesquisa.equals("Igual a")) {
                    hql = "select p from Departamento p where  p.nome = :pesquisa";
                    Query query = session.createQuery(hql);
                    query.setString("pesquisa", pesquisa);
                    results = query.list();
                }
            }
            return results;
        } finally {
            session.close();
        }
    }
}
